<template>
    <editable-table
      v-model="tableData"
      :columns="columns"
      :total="total"
      :current-page="currentPage"
      :page-size="pageSize"
      :loading="loading"
      @edit="onEdit"
      @save="onSave"
      @delete="onDelete"
      @add="onAdd"
      @cancel="onCancel"
      @load-data="loadDataFromBackend"
    />
  </template>
  
  <script setup lang="ts">
  import { ref } from 'vue'
  import EditableTable from './EditableTable.vue'
  
  // 表格列配置
  const columns = [
  { 
    label: '名称', 
    prop: 'name', 
    type: 'text',
    required: true // 必填
  },
  {
    label: '类型',
    prop: 'type',
    type: 'select',
    options: [
      { label: '酸性', value: 'acid' },
      { label: '凝胶', value: 'gel' },
      { label: '水基', value: 'water' }
    ],
    required: true // 必填
  },
  { 
    label: '配方', 
    prop: 'recipe', 
    type: 'text',
    required: false // 必填
  }
]
  
  // 分页参数
  const currentPage = ref(1)
  const pageSize = ref(5)
  const total = ref(100)
  const loading = ref(false)
  
  // 表格数据（包含新增行）
  const tableData = ref<any[]>([])
  
  // 模拟从后端获取数据
  const loadDataFromBackend = async (page: number, size: number) => {
    console.log(`加载数据: 页码=${page}, 每页=${size}`)
    loading.value = true
  
    // 这里模拟 API 请求
    setTimeout(() => {
      const newData = Array.from({ length: size }, (_, i) => ({
        name: `液体${i + 1}`,
        type: ['acid', 'gel', 'water'][Math.floor(Math.random() * 3)],
        _editing: false
      }))
  
      // 保留新增行
      const newRows = tableData.value.filter(row => row._isNew)
      tableData.value = [...newRows, ...newData]
  
      currentPage.value = page
      pageSize.value = size
      loading.value = false
    }, 500)
  }
  
  // 初始化加载第一页
  loadDataFromBackend(currentPage.value, pageSize.value)
  
  // 各个事件处理
  const onEdit = (row: any) => {
      row._editing = true
    console.log('进入编辑模式:', row)
  }
  const onSave = (row: any, index: number) => {
    console.log('保存行:', row, index)
    if (!row.name || !row.type) {
      alert('请填写完整信息')
      return
    }
    row._editing = false
  }
  const onDelete = (row: any, index: number) => {
    console.log('删除行:', row, index)
    tableData.value.splice(index, 1)
  }
  const onAdd = (row: any, index: number) => {
    console.log('确认新增:', row)
    if (!row.name || !row.type) {
      alert('请填写完整信息')
      return
    }
    row._isNew = false
    row._editing = false
  }
  const onCancel = (row: any | null, index: number) => {
    if (row && row._isNew) {
      tableData.value.splice(index, 1)
    } else if (row) {
      row._editing = false
    }
  }
  </script>